package controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import pojo.Goods;
import pojo.OrderDetail;
import pojo.OrderGoodsInfo;
import pojo.User;
import service.ICartService;
import service.IGoodsService;
import service.IOrderService;
import service.IUserService;
import service.impl.CartServiceImpl;
import service.impl.GoodsServiceImpl;
import service.impl.OrderServiceImpl;
import service.impl.UserServiceImpl;
import utils.NoLoginUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "CheckoutServlet", value = "/checkout")
public class CheckoutServlet extends HttpServlet {
    private IUserService userService;
    private IGoodsService goodsService;
    private IOrderService orderService;
    private ICartService cartService;

    @Override
    public void init() throws ServletException {
        userService = new UserServiceImpl();
        goodsService = new GoodsServiceImpl();
        orderService = new OrderServiceImpl();
        cartService = new CartServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        NoLoginUtil.doVerify(request);
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        if (username == null) {
            request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
            return;
        }
        int uid = userService.queryIdByUsername(username);
        List<Integer> countList = new ArrayList<>();
        List<Goods> goodsList = new ArrayList<>();
        BigDecimal sum = new BigDecimal("0");
        String isCart = request.getParameter("cart");
        request.setAttribute("isCart", "true".equals(isCart));
        String goods = request.getParameter("data");
        if (goods == null || "".equals(goods.trim())) {
            request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
            return;
        }
        try {
            for (Map<String, String> map : (List<Map<String, String>>) JSON.parse(goods)) {
                goodsList.add(goodsService.queryGoodsById(Integer.parseInt(map.get("gid"))));
                countList.add(Integer.parseInt(map.get("count")));
            }
        } catch (JSONException | NumberFormatException e) {
            request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
            return;
        }
        for (int i = 0; i < goodsList.size(); i++) {
            BigDecimal price = goodsList.get(i).getPrice();
            BigDecimal num = new BigDecimal(countList.get(i));
            sum = sum.add(price.multiply(num));
        }
        request.setAttribute("goodsList", goodsList);
        request.setAttribute("countList", countList);
        request.setAttribute("sum", sum);
        User user = userService.queryUserById(uid);
        request.setAttribute("user", user);
        request.getRequestDispatcher("/WEB-INF/checkout.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        if (username == null) {
            request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
            return;
        }
        int uid = userService.queryIdByUsername(username);
        String oid = System.currentTimeMillis() + "X" + uid;
        String isCart = request.getParameter("is-cart");
        if ("true".equals(isCart)) {
            cartService.clearCartByUid(uid);
        }
        String goods = request.getParameter("goods");
        String receiptName = request.getParameter("receipt-name");
        String receiptPhone = request.getParameter("receipt-phone");
        String receiptAddress = request.getParameter("receipt-address");
        String receiptNotes = request.getParameter("receipt-notes");
        String sPayType = request.getParameter("pay-type");
        String sSendType = request.getParameter("send-type");
        int payType = 1, sendType = 1;
        switch (sPayType) {
            case "门店支付":
                payType = 2;
                break;
            case "货到付款":
                payType = 3;
                break;
            default:
                break;
        }
        switch (sSendType) {
            case "千城当日达":
                sendType = 2;
                break;
            case "门店自提":
                sendType = 3;
                break;
            case "一小时加急送":
                sendType = 4;
                break;
            default:
                break;
        }
        Map<String, String> map = new HashMap<>();
        boolean b = orderService.addToOrderDetail(new OrderDetail(oid, uid, receiptName, receiptAddress, receiptPhone, payType, sendType, receiptNotes));
        if (!b) {
            map.put("isSuccess", "false");
            response.getWriter().write(JSONObject.toJSONString(map));
            return;
        }
        List<Map<String, String>> goodsList = (List<Map<String, String>>) JSON.parse(goods);
        for (Map<String, String> g : goodsList) {
            int gid = Integer.parseInt(g.get("goods_id"));
            int count = Integer.parseInt(g.get("goods_count"));
            boolean b1 = orderService.addToOrderGoodsInfo(new OrderGoodsInfo(oid, gid, count));
            if (!b1) {
                map.put("isSuccess", "false");
                response.getWriter().write(JSONObject.toJSONString(map));
                return;
            }
        }
        map.put("isSuccess", "true");
        map.put("oid", oid);
        response.getWriter().write(JSONObject.toJSONString(map));

    }
}
